package test;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;
import framework.ApplicationManager;

public class ScreenShotOnFailure extends TestListenerAdapter 
{
	@Override
	public void onTestFailure(ITestResult result) {
		TestBase.printDelimeter();
		TestBase.log.error("Упал тест: " + result.getMethod().getMethodName());
		ApplicationManager app = ApplicationManager.getInstance();
		File scrFile = app.getAuxiliaryHelper().takeScreenshot();
		String destDir = app.getProperty("pathToScreenshots");
		String destFile = composeScreenshotName(result);
		copyFileToFolder(scrFile, destDir, destFile);
		Reporter.setEscapeHtml(false);
		Reporter.log("Saved <a href=" + destDir + "/" + destFile	+ ">Screenshot</a>");
	}

	private String composeScreenshotName(ITestResult result) {
		DateFormat df = new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss");
		String destFile = df.format(new Date()) + "_" + result.getMethod().getMethodName() + ".png";
		return destFile;
	}

	private void copyFileToFolder(File scrFile, String destDir, String destFile) {
		new File(destDir).mkdirs();
		try {
			FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
